package com.gs.spider.tq;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    /**
     * 日志对象
     */
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String doGet(String url, String charset) {
        String result = null;
        HttpGet get = null;
        HttpClient httpClient;
        HttpResponse response = null;
        try {
            get = new HttpGet(url);
            get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            get.setHeader("Accept-Encoding", "gzip");
            get.setHeader("charset", charset);
            httpClient = new DefaultHttpClient();
            response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), charset);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getEntity().getContent().close();
            } catch (UnsupportedOperationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String doGetGzip(String url, String charset) {
        String result = null;
        HttpGet get = null;
        HttpClient httpClient;
        HttpResponse response = null;
        try {
            get = new HttpGet(url);
            get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            get.setHeader("Accept-Encoding", "gzip");
            get.setHeader("charset", charset);
            httpClient = new DefaultHttpClient();
            response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(new GzipDecompressingEntity(response.getEntity()), charset);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getEntity().getContent().close();
            } catch (UnsupportedOperationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static String doGet(String url, String charset, CloseableHttpClient httpClient) {
        String result = null;
        HttpGet get = null;
        CloseableHttpResponse response = null;
        try {
            get = new HttpGet(url);
            get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            get.setHeader("Accept-Encoding", "gzip");
            get.setHeader("charset", charset);
            response = httpClient.execute(get);
            System.out.println("响应状态==> " + response.toString());
            HttpEntity entity = null;
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                entity = response.getEntity();
                result = EntityUtils.toString(entity, charset);
            }
//			EntityUtils.consume(entity);
//			response.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        } finally {
            try {
                response.getEntity().getContent().close();
            } catch (UnsupportedOperationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String doGet(String url, String charset, Map<String, String> headers, HttpClient httpClient) {
        String result = null;
        HttpGet get = null;
        HttpResponse response = null;
        try {
            get = new HttpGet(url);
            get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            get.setHeader("Accept-Encoding", "gzip");
            get.setHeader("charset", charset);
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                get.setHeader(entry.getKey(), entry.getValue());
            }
            response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), charset);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getEntity().getContent().close();
            } catch (UnsupportedOperationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取文件流
     *
     * @param src
     * @param httpclient
     * @return
     */
    public static InputStream doGetStream(String src, HttpClient httpclient) {
        InputStream in = null;
        HttpResponse response = null;
        try {
            HttpGet httpget = new HttpGet(src);
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            in = entity.getContent();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取文件流出错，地址：{}", src);
        } finally {
            try {
                response.getEntity().getContent().close();
            } catch (UnsupportedOperationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return in;
    }

    public static String doPost(String url, String charset, Map<String, String> param) {
        return doPost(url, charset, param, HttpClients.custom().build());
    }

    public static String doPost(String url, String charset, Map<String, String> param, HttpClient client) {

        String result = null;
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        post.setHeader("Accept-Encoding", "gzip");
        post.setHeader("charset", charset);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        HttpResponse res = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs, charset));
            res = client.execute(post);
            result = EntityUtils.toString(res.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                res.getEntity().getContent().close();
            } catch (UnsupportedOperationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static CloseableHttpResponse doPostRes(String url, String charset, Map<String, String> param, Map<String, String> headers, CloseableHttpClient client) {

        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        post.setHeader("Accept-Encoding", "gzip");
        post.setHeader("charset", charset);
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            post.setHeader(entry.getKey(), entry.getValue());
        }
        CloseableHttpResponse res = null;
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs, charset));
            res = client.execute(post);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    public static String doPost(String url, String charset, Map<String, String> param, Map<String, String> headers, HttpClient client) {

        String result = null;
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        post.setHeader("Accept-Encoding", "gzip");
        post.setHeader("charset", charset);
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            post.setHeader(entry.getKey(), entry.getValue());
        }

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        HttpResponse res = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs, charset));
            res = client.execute(post);
            result = EntityUtils.toString(res.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                res.getEntity().getContent().close();
            } catch (UnsupportedOperationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String doPostHeader(String url, String charset, Map<String, String> headers, HttpClient client) {

        String result = null;
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        post.setHeader("Accept-Encoding", "gzip");
        post.setHeader("charset", charset);
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            post.setHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse res = null;
        try {
            res = client.execute(post);
            result = EntityUtils.toString(res.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                res.getEntity().getContent().close();
            } catch (UnsupportedOperationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String doPost(String url, String charset, JSONObject json, HttpClient client) {

        String result = null;
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        post.setHeader("Accept-Encoding", "gzip");
        post.setHeader("charset", charset);
        StringEntity s = null;
        s = new StringEntity(JSONObject.toJSONString(json), charset);
        s.setContentType("application/json");
        HttpResponse res = null;
        try {
            post.setEntity(s);
            res = client.execute(post);
            result = EntityUtils.toString(res.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                res.getEntity().getContent().close();
            } catch (UnsupportedOperationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
